import "reflect-metadata";
import { config } from "../config";
import { DataSource } from "typeorm";
import { Enum } from "@/share/enums/enum";
import { utils } from "@/utils";
import * as Model from "@/share/models";

export const db = new DataSource({
  type: config.database.type,
  host: config.database.host,
  port: config.database.port,
  username: config.database.username,
  password: config.database.password,
  database: config.database.database,
  charset: "utf8mb4",
  entities: Object.values(Model),
  synchronize: true,
  dateStrings: true,
  logging: false
});

db.initialize()
  .then(async () => {
    const userRepository = db.getRepository(Model.UserModel);
    const admin = await userRepository.findOneBy({ username: "admin" });
    if (!admin) {
      const user = new Model.UserModel();
      user.username = "admin";
      user.password = utils.md5("admin123");
      user.nickname = "管理员";
      user.role = Enum.Role.Admin;
      user.createBy = "system";
      user.updateBy = "system";
      await userRepository.save(user);
    }
  })
  .catch(error => {
    throw error;
  });
